package com.xgkj.diyiketang.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;


/**
 * Created by windo on 16/8/17.
 */
public class ShareUtil implements View.OnClickListener{
    private Context mContext;
    private static ShareUtil instance;
    private PopupWindow popWindow;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    public static Tencent mTencent;
    private String share_title;
    private String weibouserid;
    private String share_url;

    public ShareUtil(Context context) {
        mContext = context;


        initPopWindow();
    }


    public static ShareUtil getInstance(Context context){
        if (instance == null){
            instance = new ShareUtil(context);
        }

        return instance;
    }

    public void show(String title, String url, PopupWindow.OnDismissListener listener,View v){
        share_title = title;
        share_url = url;
        popWindow.setOnDismissListener(listener);
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.share_to_timeline:

                String sharepath2 = share_url;
                shareToWeiXin(sharepath2, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                String sharepath = share_url;
                shareToWeiXin(sharepath, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                String sharepath3 = share_url;
                shareToWeiBo(sharepath3);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
//                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
//                weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);

                shareToqq();
                popWindow.dismiss();
                break;
        }
    }

    private void shareToqq() {
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, mContext.getApplicationContext());  //1104548348
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);

        String sharepath5 = share_url;
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, sharepath5);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
        // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
        mTencent.shareToQQ((Activity) mContext, params, qqShareListener);
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };

    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, mContext.getApplicationContext());  //1104548348
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);

        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }
//        if (mWeixinShareReceive != null) {
//            unregisterReceiver(mWeixinShareReceive);
//            mWeixinShareReceive = null;
//        }
//
//        if (mWeixinShareReceive == null) {
//            mWeixinShareReceive = new WeixinShareReceive();
//            IntentFilter filter = new IntentFilter();
//            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
//            registerReceiver(mWeixinShareReceive, filter);
//        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.app_icon);
        byte[] weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }


    private void shareToWeiBo(String webpage) {
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mContext,
                ProtocolConst.WEIBO_APP_KEY);//这粒要换
        mWeiboShareAPI.registerApp();
//        if (mWeixinShareReceive != null) {
//            unregisterReceiver(mWeixinShareReceive);
//            mWeixinShareReceive = null;
//        }
//
//        if (mWeixinShareReceive == null) {
//            mWeixinShareReceive = new WeixinShareReceive();
//            IntentFilter filter = new IntentFilter();
//            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
//            registerReceiver(mWeixinShareReceive, filter);
//        }
//		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // if (hasText) {
        // weiboMessage.mediaObject = getTextObj();
        // }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
        if (!TextUtils.isEmpty(webpage)) {
            TextObject textobject = new TextObject();
            textobject.text = share_title;
            weiboMessage.textObject = textobject;
            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = Utility.generateGUID();
            mediaObject.defaultText = "第一课堂";
            mediaObject.title = "第一课堂";
            mediaObject.description = share_title;
            mediaObject.actionUrl = webpage;
//            if (weiboShareBitmap != null) {
//                mediaObject.setThumbImage(weiboShareBitmap);
//            } else {
            mediaObject.setThumbImage(BitmapFactory.decodeResource(
                    mContext.getResources(), R.drawable.app_icon));
//            }
            weiboMessage.mediaObject = mediaObject;
        }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
            /*
             * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
			 */

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(mContext, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(mContext.getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
        mWeiboShareAPI.sendRequest((Activity) mContext, request, authInfo, token, new WeiboAuthListener() {


            @Override
            public void onWeiboException(WeiboException arg0) {
            }

            @Override
            public void onComplete(Bundle bundle) {
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(mContext.getApplicationContext(), newToken);
                weibouserid = newToken.getUid();
//                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
            }

            @Override
            public void onCancel() {
            }
        });


    }
}
